/**
 * dbconnections js file;
 * company:junqitecch
 * author:xuzuiotao
 * handling response information
 */

//数据库连接通过连接池
const mysql=require("mysql");//引入mysql模块
const pool = mysql.createPool(global.consts.MySQL);

class JQMySqlConnction{
	constructor() {
	    
		
	}
	static async instance(){
		// console.log('mysqlconnection :::1111');
		let obj = new JQMySqlConnction();
		// console.log('mysqlconnection :::222');
		obj.conn = await obj.createDB();
		// console.log('mysqlconnection :::3333');
		return obj;
	}
	
	async createDB(){
		console.log('createDB::11111'+'\r\n' );
	
		let promise = new Promise((resolve, reject)=>{
			pool.getConnection((err,conn)=>{
			        if(err){
		        		resolve(null);
			        }else{
			        	conn.query('SET SQL_SAFE_UPDATES=0', function(qerr,vals,fields){
			        		if(qerr){
			        			releaseDB(conn);
			        			resolve(null);
			        			return;
			        		}
							console.log('createDB::2222'+'\r\n' );
								
							this.conn = conn;
			        		resolve(conn);
			        	});
			        }
			 
			 });
		});
	
		return promise;
	}
	
	async  readDB(sql,params){
		console.log('readDB::before '+new Date().format('yyyy-MM-dd hh:mm:ss')+ sql+ '\r\n' );
		var promise = new Promise((resolve, reject)=>{
			this.conn.query(sql,params,
					function(qerr,result,fields){
				
				if(qerr){
					console.log('readDB::'+ JSON.stringify(qerr)+'');//JSON.stringify(result));
	
					resolve(null);
					return;
				}
				resolve(result);
			});
		});
	
		return promise;
	};
	
	async  writeDB(sql,params){
		console.log('writeDB::before'+new Date().format('yyyy-MM-dd hh:mm:ss')+ sql+ '\r\n' );
	
		var promise = new Promise((resolve, reject)=>{
			this.conn.query(sql,params,
					function(qerr,result,fields){
			
				if(qerr){
					console.log('writeDB::'+ JSON.stringify(qerr)+'');//JSON.stringify(result));
	
					resolve(null);
					return;
				}
				resolve(result);
			});
		});
	
		return promise;
	}
	
	async  updateDB(sql,params){
		console.log('updateDB::before'+new Date().format('yyyy-MM-dd hh:mm:ss')+ sql+ '\r\n' );
	
		var promise = new Promise((resolve, reject)=>{
			this.conn.query(sql,params,
					function(qerr,result,fields){
				
				if(qerr){
					console.log('updateDB::error::'+ JSON.stringify(qerr)+'');//JSON.stringify(result));
					resolve(null);
					return;
				}
				
				console.log('upateDB::ok::'+JSON.stringify(result));
				resolve(result);
			});
		});
	
		return promise;
	}
	 releaseDB(){
		console.log('releaseDBnew');
		//pool.releaseConnection(db);
		if(this.conn)this.conn.release();
		else console.log('release conn null');
	}
	
}


module.exports=JQMySqlConnction;
